package org.zezs.sync.mongo.plugs.bank;

import com.alibaba.fastjson.JSON;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import jdk.nashorn.api.scripting.NashornScriptEngine;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zezs.sync.mongo.Constants;
import org.zezs.sync.mongo.config.mongo.MongoUtil;
import org.zezs.sync.mongo.plugs.Plug;

import javax.script.ScriptException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class BankLocationCache  extends Plug {
	public static Logger logger = LoggerFactory.getLogger(BankLocationCache.class);

	public static int[] cardPrefixLengthType = {10, 9, 8, 7, 6, 5, 4, 3, 2};

	static Map<String, BankLocation> locationMap=new HashMap<>();

	public static Map<String, BankLocation>  getBankMap() {
		synchronized (locationMap){
			if(locationMap.isEmpty()){
				logger.info("初始身份证定位");
				MongoCollection<Document> collection = MongoUtil.getMongoDb("paramConfig").getCollection("bank_location");
				List<BankLocation> bankLocations=new LinkedList<>();
				FindIterable<Document> documents = collection.find();
				MongoCursor<Document> iterator = documents.iterator();
				while (iterator.hasNext()){
					Document next = iterator.next();
					BankLocation bankLocation = JSON.parseObject(next.toJson(), BankLocation.class);
					locationMap.put(bankLocation.getBank_code(), bankLocation);
				}

				logger.info("初始身份证信息结束{}", locationMap.size());
			}
		}

		return  locationMap;
	}

	@Override
	public void init(NashornScriptEngine engine) {
		try {
			this.jsFile="/plugs/bankLocation.js";
			initJs(engine);
			engine.invokeFunction("setBankCache", BankLocationCache.getBankMap());
		} catch (ScriptException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}

	}
}
